package mk.gamemap.model
{
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import game.tileMap.model.vo.MapObj;
	
	public class TileMapModel0 extends EventDispatcher
	{
		public var view_arr:Array;
		public var tiles:Array;
		public var passage_arr:Array  
		public var mapData:MapData;
		public var mapSprites:Array;
		public var player:Player;
		
		public var maxX:int;
		public var maxY:int;
		public function TileMapModel0()
		{
			setup("1")
		}
		
		public function setup(map_id:String):void{
//			@map_id = map_id
//				@map = load_data(sprintf("Data/Map%03d.rvdata", @map_id))
//				@display_x = 0
//				@display_y = 0
//				@passages = $data_system.passages
			mapData=MapFactory.creatMap(map_id);
			tiles=new Array();
			var tileType_arr:Array=mapData.type_arr
			maxX=tileType_arr.length-1
			maxY=tileType_arr[i].length-1;
			for (var i:int=0;i<tileType_arr.length;i++){
				tiles[i]=new Array();
				for (var j:int=0;j<tileType_arr[i].length;j++){
					tiles[i][j]=(new Tile(i,j,tileType_arr[i][j]));
					if (tileType_arr[i][j]>=3){
						tiles[i][j].passable=false;
					}
				}
			}	
//				
			setupEvents()
//			setup_scroll
//			setup_parallax
		}
		
		public function setupEvents():void{
//			
			/*@common_events = {}   # 公共事件
			for i in 1...$data_common_events.size
				@common_events[i] = Game_CommonEvent.new(i)
			end*/
			mapSprites=[];
			if (player){
				mapSprites.push(player);
			}
			var mapSp:MapObj
			
			for each(var xml:XML in mapData.getSpriteXml().sp){	
				trace(xml,"data"+xml.@id)
				var passable:Boolean=Boolean(int(xml.@passable))
				mapSp=MapFactory.creatMapSprite(xml.@id,this,xml.@x,xml.@y,passable,xml.@event);
				if (!player){
					if (mapSp is Player){
						player=mapSp as Player;
						mapSprites.push(player);
					}
					
				}
				if (!(mapSp is Player)){
					mapSprites.push(mapSp);
				}
			}
			
			
		}
		
		public function getSp_xy(x:int, y:int):MapObj{
			var result:MapObj
			var i:int=0
			for each(var mapSp:MapObj in mapSprites){	
				i++
					trace(mapSp+"=="+mapSp.x+"事触！"+mapSp.y)
				 if (mapSp.onPos(x, y)){
					 if (mapSp!=player){
						 result=mapSp
					 }
					
				}
			}		
			return result
			
		}
		
		public function setDisplayPos(x, y):void{
			/*@display_x = (x + @map.width * 256) % (@map.width * 256)
				@display_y = (y + @map.height * 256) % (@map.height * 256)
				@parallax_x = x
				@parallax_y = y*/
		}
		
		
		//位置XY是否允许通过
		public function passable(x:int, y:int, flag:int = 0x01):Boolean{
			if (x<0||y<0||x>maxX||y>maxY){
				return false;
			}
			for each(var mapSp:MapObj in mapSprites){
				if (mapSp.x==x&&mapSp.y==y){
					return mapSp.through;
				}
			}
			if (x>=0&&y>=0){
				var tile:Tile = tiles[x][y]     
				if (tile){
					return tile.passable;
				}  
			}
			  
			
			return true;
		}
		
		
	}
}